package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加菜品
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        //调用service层方法,添加数据库
        categoryService.save(category);

        //分页查询
        return R.success("添加成功");

    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page<Category>> page(Integer page, Integer pageSize, String name) {
        //1.创建一个分页对象Page
        Page<Category> pageInfo = new Page<>(page, pageSize);

        //2.直接调用service层分页查询数据
        categoryService.lambdaQuery()
//                       //过滤条件 StringUtils.isNotBlank() 判断是否为空
//                       .like(StringUtils.isNotBlank(name), Category::getName, name)
                .orderByAsc(Category::getSort)  //排序字段升序
                .orderByDesc(Category::getUpdateTime) //排序条件修改时间降序
                .page(pageInfo); //分页查询

        //3.响应数据
        return R.success(pageInfo);
    }

    /**
     * 根据id删除分类
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(Long id) {

        categoryService.deleteById(id);
        return R.success("删除成功");

    }

    /**
     * 根据id修改分类信息
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 根据type查询
     *
     * @param type
     * @return
     */
    @GetMapping("list")
    public R<List<Category>> list(Integer type) {
        //查询数据 select * from category where type=?
        List<Category> list = categoryService.query()
                .eq(type != null, "type", type)
                .orderByAsc("sort")
                .orderByDesc("update_time")
                .list();

        return R.success(list);
    }
}
